package application

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
)

// chclient的事情
// InitCC 链码初始化
func (a *Application) InitCC(channelId, orgName, userName, chaincodeID string, initFcn string) error {
	// 检查参数
	fmt.Println("=====InitCC=====", userName)
	channelId, orgName, userName, err := a.LeAndChClientParams(channelId, orgName, userName)
	fmt.Println("=====InitCC=====", userName)
	if err != nil {
		return fmt.Errorf("InitCC err:%v", err)
	}
	// 获取org实例
	org, ok := a.Channels[channelId].Orgs[orgName]
	if !ok {
		return fmt.Errorf("InitCC err:获取org实例失败.")
	}
	// 调用链码
	err = org.InitCC(a.FabSDK, channelId, userName, chaincodeID, initFcn)
	if err != nil {
		return fmt.Errorf("InitCC err:%v", err)
	}
	return nil
}

// InvokeCC 调用链码
func (a *Application) InvokeCC(channelId, orgName, userName, chaincodeID string, fcn string, args []string) (*channel.Response, error) {
	// 检查参数
	fmt.Println("=====InvokeCC=====", userName)
	channelId, orgName, userName, err := a.LeAndChClientParams(channelId, orgName, userName)
	fmt.Println("=====InvokeCC=====", userName)
	if err != nil {
		return nil, fmt.Errorf("InvokeCC err:%v", err)
	}
	// 获取org实例
	org, ok := a.Channels[channelId].Orgs[orgName]
	if !ok {
		return nil, fmt.Errorf("InvokeCC err:获取org实例失败.")
	}
	// 调用链码
	fmt.Println("=====InvokeCC chaincode=====", chaincodeID)
	fmt.Println("=====InvokeCC fcn=====", fcn)
	response, err := org.ChaincodeInvoke(a.FabSDK, channelId, userName, chaincodeID, fcn, args)
	if err != nil {
		return nil, fmt.Errorf("InvokeCC err:%v", err)
	}
	return response, nil
}

// QueryCC 查询链码
func (a *Application) QueryCC(channelId string, orgName, userName string, chaincodeID string, fcn string, args []string) (*channel.Response, error) {
	// 检查参数
	fmt.Println("===QueryCC channelId===", channelId)
	channelId, orgName, userName, err := a.LeAndChClientParams(channelId, orgName, userName)
	if err != nil {
		return nil, fmt.Errorf("channelId err:%v", err)
	}
	// 获取org实例
	org, ok := a.Channels[channelId].Orgs[orgName]
	if !ok {
		return nil, fmt.Errorf("channelId err:获取org实例失败.")
	}
	// 调用链码
	response, err := org.ChaincodeQuery(a.FabSDK, channelId, userName, chaincodeID, fcn, args)
	if err != nil {
		return nil, fmt.Errorf("channelId err:%v", err)
	}
	return response, nil
}
